<script lang="ts" setup>
import { ref, watch, computed, defineProps, defineEmits } from 'vue';
import { useFilesStore } from '@/store/files';
import { ElMessage } from 'element-plus';
import { Plus, Search, Delete, Download, Document } from '@element-plus/icons-vue';
import { $t } from '@/plugins/i18n';

// 定义组件的属性和事件
const props = defineProps({
  modelValue: {
    type: Array,
    default: () => []
  }
});

const emit = defineEmits(['update:modelValue']);

// 初始化文件商店
const filesStore = useFilesStore();
const loading = ref(false);
const searchForm = ref({
  filename: '',
  filepath: '',
  fileType: ''
});

// 表格选择
const selectedFiles = ref([]);

// 计算当前选中文件
const currentSelectedFiles = computed({
  get: () => props.modelValue,
  set: (value) => {
    emit('update:modelValue', value);
  }
});

// 监听表格选择变化，更新组件绑定值
watch(selectedFiles, (newValue) => {
  currentSelectedFiles.value = [...newValue];
});

// 搜索文件
const searchFiles = async () => {
  loading.value = true;
  try {
    await filesStore.getFilesList();
  } catch (error) {
    console.error('获取文件列表失败:', error);
    ElMessage.error('获取文件列表失败');
  } finally {
    loading.value = false;
  }
};

// 重置搜索表单
const resetSearchForm = async () => {
  searchForm.value = {
    filename: '',
    filepath: '',
    fileType: ''
  };
  filesStore.form = { ...searchForm.value };
  await searchFiles();
};

// 组件加载时获取文件列表
searchFiles();

// 格式化文件类型
const formatFileType = (type) => {
  if (!type) return '未知类型';
  
  // 文件类型映射
  const typeMap = {
    'application/vnd.openxmlformats-officedocument.wordprocessingml.document': 'Word文档 (DOCX)',
    'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': 'Excel表格 (XLSX)',
    'application/vnd.openxmlformats-officedocument.presentationml.presentation': 'PowerPoint (PPTX)',
    'application/pdf': 'PDF文档',
    'application/msword': 'Word文档 (DOC)',
    'application/vnd.ms-excel': 'Excel表格 (XLS)',
    'application/vnd.ms-powerpoint': 'PowerPoint (PPT)',
    'text/plain': '文本文件',
    'image/jpeg': 'JPEG图片',
    'image/png': 'PNG图片',
    'image/gif': 'GIF图片',
    'text/html': 'HTML文件',
    'application/json': 'JSON文件',
    'application/xml': 'XML文件'
  };
  
  return typeMap[type] || type;
};
</script>

<template>
  <div class="system-files-selector">
    <!-- 搜索表单 -->
    <el-form :inline="true" :model="searchForm" class="search-form mb-4">
      <el-form-item :label="$t('files_filename')" prop="filename">
        <el-input 
          v-model="searchForm.filename" 
          v-model:modelValue="filesStore.form.filename"
          :placeholder="`${$t('input')}${$t('files_filename')}`" 
          class="!w-[180px]" 
          clearable 
        />
      </el-form-item>
      <el-form-item :label="$t('files_filepath')" prop="filepath">
        <el-input 
          v-model="searchForm.filepath" 
          v-model:modelValue="filesStore.form.filepath"
          :placeholder="`${$t('input')}${$t('files_filepath')}`" 
          class="!w-[180px]" 
          clearable 
        />
      </el-form-item>
      <el-form-item :label="$t('files_fileType')" prop="fileType">
        <el-input 
          v-model="searchForm.fileType" 
          v-model:modelValue="filesStore.form.fileType"
          :placeholder="`${$t('input')}${$t('files_fileType')}`" 
          class="!w-[180px]" 
          clearable 
        />
      </el-form-item>
      <el-form-item>
        <el-button :icon="Search" :loading="loading" type="primary" @click="searchFiles">
          {{ $t('search') }}
        </el-button>
        <el-button :icon="Delete" @click="resetSearchForm">
          {{ $t('buttons.reset') }}
        </el-button>
      </el-form-item>
    </el-form>

    <!-- 文件列表表格 -->
    <el-table
      v-loading="loading"
      :data="filesStore.datalist"
      border
      style="width: 100%"
      @selection-change="selectedFiles = $event"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column label="文件名" prop="filename" min-width="200">
        <template #default="{ row }">
          <div class="flex items-center">
            <el-icon class="mr-2"><Document /></el-icon>
            {{ row.filename }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="文件类型" prop="fileType" min-width="150">
        <template #default="{ row }">
          <el-tag size="small" effect="plain">{{ formatFileType(row.fileType) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="文件路径" prop="filepath" min-width="200" />
      <el-table-column label="文件大小" prop="fileSize" min-width="100">
        <template #default="{ row }">
          {{ Math.floor(row.fileSize / 1024) }}KB
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container mt-4 flex justify-end">
      <el-pagination
        v-model:current-page="filesStore.pagination.currentPage"
        v-model:page-size="filesStore.pagination.pageSize"
        :page-sizes="filesStore.pagination.pageSizes"
        :total="filesStore.pagination.total"
        background
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="searchFiles"
        @current-change="searchFiles"
      />
    </div>

    <!-- 已选文件列表 -->
    <div v-if="currentSelectedFiles.length > 0" class="selected-files mt-6">
      <h4 class="text-base font-medium mb-2">已选择的文件</h4>
      <el-table :data="currentSelectedFiles" border style="width: 100%">
        <el-table-column label="文件名" prop="filename" min-width="200" />
        <el-table-column label="文件类型" prop="fileType" min-width="150">
          <template #default="{ row }">
            <el-tag size="small" effect="plain">{{ formatFileType(row.fileType) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100">
          <template #default="{ $index }">
            <el-button type="danger" link @click="currentSelectedFiles.splice($index, 1)">
              <el-icon><Delete /></el-icon>
              移除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.system-files-selector {
  width: 100%;
  height: 100%;
}
</style> 